/**
 * Created with IntelliJ IDEA.
 * Description:给定一个有序整型数组, 实现二分查找
 * User: xwl
 * Date: 2023-04-05
 * Time: 21:35
 */
public class Test3 {
    public static void main(String[] args) {
        //定义一个数组
        int[] array = {1,2,3,4,5,6,7,8,9};
        //调用方法
        binarySearch(array,7);
        binarySearch(array,10);

    }
    //实现二分查找
    public static int binarySearch(int[] array,int dest) {
        //定义俩个变量分别代表数组的左右下标
        int left = 0;
        int right = array.length - 1;
        //实现二分查找
        while (left < right) {
            if (array[(right + left) / 2] < dest) {
                left = (right + left) / 2 + 1;
            } else if (array[(right + left) / 2] > dest) {
                right = (right + left) / 2 - 1;
            } else {
                System.out.println("查找成功，" + dest + "的下标是：" + (right + left) / 2);
                return (right + left) / 2;
            }
        }
        //没找到进行处理
        if(left >= right) {
            System.out.println(dest+"在数组中不存在");
            return -1;
        }
        return 0;
    }
}
